<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          总记录数: {{ total }} 条
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showAddDialog">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table :data="tableData" border stripe>
          <el-table-column type="index" :index="indexMethods" label="序号" />
          <el-table-column sortable prop="username" label="姓名" />
          <el-table-column sortable prop="staffPhoto" label="头像" />
          <el-table-column sortable prop="workNumber" label="工号" />
          <el-table-column sortable prop="mobile" label="手机号" />
          <el-table-column sortable label="聘用形式" prop="formOfEmployment" :formatter="formatter" />
          <el-table-column sortable prop="departmentName" label="部门" />
          <el-table-column sortable prop="timeOfEntry" label="入职日期">
            <template #default="{row}">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250px">
            <template #default="{row}">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="query.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <AddEmployess :dialog-visible.sync="dialogVisible" @render="getUserList" />
    </div>
  </div>
</template>

<script>
import employeesConstant from '@/constant/employees'
import { reqDelEmployees, reqGetEmployeesList } from '@/api/employees'
import AddEmployess from './components/AddEmployess.vue'
import { formatTime } from '@/filter'
export default {
  name: 'Employees',
  components: {
    AddEmployess
  },
  data() {
    return {
      dialogVisible: false, // 对话框
      tableData: [], // 表格数据,
      total: 0, // 所有条数,
      query: { // 请求数据
        page: 1,
        size: 5
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取员工列表
    async getUserList() {
      const { data } = await reqGetEmployeesList(this.query)
      this.total = data.total
      this.tableData = data.rows
    },
    // 处理表单序号
    indexMethods(index) {
      return index + 1 + (this.query.page - 1) * this.query.size
    },
    handleSizeChange(val) {
      this.query.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getUserList()
    },
    // 表单格式化程序
    formatter(row, column) {
      const obj = employeesConstant.hireType.find(item => item.id === +row.formOfEmployment)
      return obj ? obj.value : '未知'
    },
    // 展示添加员工对话框
    showAddDialog() {
      this.dialogVisible = true
    },
    // 根据ID删除员工
    async  del(id) {
      const res = await this.$confirm('您确定要删除当前员工吗', '删除提示', {
        type: 'warning'
      }).catch(() => {})
      if (res !== 'confirm') return this.$message.info('已取消操作')
      await reqDelEmployees(id)
      if (this.tableData.length === 1 && this.query.page > 1) {
        this.query.page--
      }
      this.getUserList()
    },
    // 导出员工execl列表
    async  handleDownload() {
      // 开启导出按钮禁用
      this.downloadLoading = true

      const { data: { rows }} = await reqGetEmployeesList(1, this.total)
      // console.log(rows)
      // 中英对照关系
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const array = this.get2Array(rows, headersRelations)
      console.log(array)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headersRelations), // 表格的标题
          // 表格的内容, 要求表格的内容是一个二维数组
          // 外层的数组控制的是下载的行的顺序, 内容的数组控制的单元格的顺序
          data: array,
          filename: '公司员工信息表', // 下载excel表格的名称
          autoWidth: true, // 自适应宽度
          bookType: 'xlsx', // 下载execl表格的扩展名
          multiHeader, // 多表头
          merges // 合并配置项
        })
        this.downloadLoading = false
      })
    },
    // 将员工列表数组处理成二维数组的方法
    get2Array(rows, headersRelations) {
    // rows是员工列表 [{}] headersRelations 中英对照关系
      return rows.map(item => {
        const arr = []
        // console.log(item)
        Object.keys(headersRelations).map(str => {
          const englishKey = headersRelations[str]
          // 导出表格后字段处理
          // 1. 日期
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            item[englishKey] ? arr.push(formatTime(item[englishKey])) : arr.push('待定')
          } else if (englishKey === 'formOfEmployment') {
            // console.log(item[englishKey])
            // console.log(employeesConstant.hireType)
            const o = employeesConstant.hireType.find(obj => obj.id === +item[englishKey])
            o ? arr.push(o.value) : arr.push('暂无')
          } else {
            arr.push(item[englishKey])
          }
        })
        return arr
      })
    }
  }
}
</script>

<style>

</style>

